package com.gzdh.device.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzdh.device.system.entity.SysRole;
import com.gzdh.device.system.entity.SysRolePermission;
import com.gzdh.device.system.entity.SysUser;
import com.gzdh.device.system.mapper.SysRoleMapper;
import com.gzdh.device.system.mapper.SysUserMapper;
import com.gzdh.device.system.service.SysRolePermissionService;
import com.gzdh.device.system.service.SysRoleService;
import com.gzdh.device.system.service.SysUserService;
import com.gzdh.device.system.vo.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements SysRoleService {

    @Autowired
    SysRolePermissionService sysRolePermissionService;

    @Override
    public IPage<RoleVO> getRoleListByPage(int pageNo, int pageSize) {
        Page<SysRole> sysRolePage = new Page<>();
        sysRolePage.setCurrent(pageNo);
        sysRolePage.setSize(pageSize);
        IPage<SysRole> sysRoleIPage = this.page(sysRolePage);
        IPage<RoleVO> roleVOIPage = new Page<>();
        roleVOIPage.setSize(sysRoleIPage.getSize());
        roleVOIPage.setPages(sysRoleIPage.getPages());
        roleVOIPage.setTotal(sysRoleIPage.getTotal());
        roleVOIPage.setCurrent(sysRoleIPage.getCurrent());
        roleVOIPage.setRecords(new ArrayList<>());
        List<SysRolePermission> sysRolePermissionList = sysRolePermissionService.list();

        for (SysRole goo : sysRoleIPage.getRecords()) {
            List<SysRolePermission> sysRolePermissions = sysRolePermissionList.stream().filter(sysRolePermission -> sysRolePermission.getRoleId().equals(goo.getId()))
                    .collect(Collectors.toList());
            List<String> stringList = new ArrayList<>();
            for (SysRolePermission goo2 : sysRolePermissions) {
                stringList.add(goo2.getPermissionId());
            }
            RoleVO roleVO = new RoleVO();

            BeanUtil.copyProperties(goo, roleVO);
            roleVO.setMenu(stringList);
            roleVOIPage.getRecords().add(roleVO);
        }
        return roleVOIPage;
    }
}
